package com.suredy.config.ctrl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.suredy.core.ctrl.BaseCtrl;
import com.suredy.core.model.Dictionary;
import com.suredy.core.service.DictionarySrv;

@Controller
@RequestMapping(value = "/config/dic")
public class DictionaryConfigCtrl extends BaseCtrl {

	@Autowired
	private DictionarySrv dictionarySrv;

	@RequestMapping(value = "/list/{dicCode}", method = RequestMethod.GET)
	public String list(@PathVariable String dicCode, Model model) {
		String view = "app/dictionary/list";

		if (StringUtils.isBlank(dicCode)) {
			model.addAttribute("invalidDicCode", true);
			return view;
		}

		List<Dictionary> data = this.dictionarySrv.getDics(dicCode);

		model.addAttribute("dicCode", dicCode);
		model.addAttribute("data", data);

		return view;
	}

	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@ResponseBody
	public boolean delete(String[] id) {
		if (id == null || id.length <= 0)
			return true;

		int count = this.dictionarySrv.delete(id);

		return count > 0;
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public boolean add(String dicCode, String dicValue) {
		if (StringUtils.isBlank(dicCode) || StringUtils.isBlank(dicValue))
			return false;

		Dictionary dic = new Dictionary();
		dic.setGroupCode(dicCode);
		dic.setVal(dicValue);

		this.dictionarySrv.save(dic);

		return true;
	}

}
